<template>
    <div class="create-post-page">
      
      
      <h4>{{ isEditMode ? '编辑文章' :  '新建文章'}}</h4>
      <!-- <input type="file" name="file" @change.prevent="handleFileChange"> -->
      <uploader actions="/upload" 
      @file-uploaded="handleFileUploaded"
      @file-uploaded-error="onFileUploadedError"
      class="d-flex align-item-center justify-content-center bg-light text-secondary w-100 my-4 text-center"
      :uploaded="uploadedData"
      :beforeUnload="uploadCheck"

      >
      <h2>点击上传头图</h2>
      <template #loading >
      <!-- <div class="d-flex">
        <div class="spinner-border text-secondary" role="status">
            <span class="sr-only">Loading...</span>
          </div>
          <h2>正在上传</h2>
      </div> -->
      <div class="wrapper">
        <div class="circle"></div>
        <div class="circle"></div>
        <div class="circle"></div>
        <div class="shadow"></div>
        <div class="shadow"></div>
        <div class="shadow"></div>
        <span>Loading</span>
    </div>

     </template>
    <template #uploaded ="dataProps" >
      <img :src="dataProps.uploadedData.data.url" width="500">

    </template>

    </uploader>


      <validate-form @form-submit="onFormSubmit">
        <div class="mb-3">
          <label class="form-label">文章标题：</label>
          <validate-input
            :rules="titleRules" v-model="titleVal"
            placeholder="请输入文章标题"
            type="text"
          />
        </div>
        <div class="mb-3">
          <label class="form-label">文章详情：</label>
          <validate-input
            rows="18"
            type="text"
            tag="textarea"
            placeholder="请输入文章详情"
            :rules="contentRules"
            v-model="contentVal"
          />
        </div>
        <template #submit>
          <button class="btn btn-primary btn-large">{{isEditMode ? '更新文章' : '发表文章'}}</button>
        </template>
      </validate-form>
    </div>
  </template>
  
  <script lang="ts">
  import Uploader from '@/components/Uploader.vue'
  import { defineComponent, ref,onMounted } from 'vue'
  import { Store, useStore } from 'vuex'
  import { useRoute, useRouter } from 'vue-router'
  import ValidateInput, { RulesProp } from '../components/ValidateInput.vue'
  import ValidateForm from '../components/ValidateForm.vue'
  import { GlooalDataProps } from '@/store'
  import { PostProps ,ResponseType ,ImageProps} from '../store'
  import axios from 'axios'
  import createMessage from '@/components/createMessage'
  import { beforeUploadCheck } from '@/helper'

  export default defineComponent({
   
    name: 'Login',
    components: {
      ValidateInput,
      ValidateForm,
      Uploader
    },
    setup() {
      const uploadedData = ref()
      const route = useRoute()
      const isEditMode  =  !!route.query.id
      const titleVal = ref('')
      const router = useRouter()
      const store = useStore<GlooalDataProps>()
      let imageId = ''
      const titleRules: RulesProp = [
        { type: 'required', message: '文章标题不能为空' }
      ]
      const contentVal = ref('')
      const contentRules: RulesProp = [
        { type: 'required', message: '文章详情不能为空' }
      ]
      const handleFileUploaded = (rawData:ResponseType<ImageProps>)=>{
        if(rawData.data._id){
          imageId = rawData.data._id
        }


      }
      onMounted(()=>{
        if(isEditMode){
          store.dispatch('fetchPostDetail',route.query.id).then((rawData:ResponseType<PostProps>)=>{
            const currentPost = rawData.data
            if(currentPost.image){
              uploadedData.value = {data:currentPost.image}
            }
            titleVal.value = currentPost.title
            contentVal.value = currentPost.content || ''
          })
        } 
        // else {
        //   store.dispatch('createPost').then((rawData:ResponseType<PostProps>)=>{
        //     const currentPost = rawData.data
        //     if(currentPost.image){
        //       uploadedData.value = {data:currentPost.image}
        //     }
        //     titleVal.value = currentPost.title
        //     contentVal.value = currentPost.content || ''
        //   })
        // }
        // store.dispatch('fetchPostDetail',route.query.id).then((rawData:ResponseType<PostProps>)=>{
        //   const currentPost = rawData.data
        //   if(currentPost.image){
        //     uploadedData.value = {data:currentPost.image}
        //   }
        //   titleVal.value = currentPost.title
        //   contentVal.value = currentPost.content || ''
        // })
      })
      const onFormSubmit = (result: boolean) => {
        if (result) {
         const { column , _id } =store.state.user
         if(column){
            const newPost:PostProps ={
            // _id:new Date().getTime().toString(),
            title:titleVal.value,
            content:contentVal.value,
            column:column.toString(),
            // createdAt:new Date().toLocaleDateString(),
            author:_id
         }
         if(imageId){
          newPost.image = imageId
         }
         const actionName = isEditMode ? ' updatePost' : ' createPost'
         const sendData = isEditMode ? {
          id:route.query.id,
          payload:newPost
         } : newPost
        // 具体store逻辑不对
         store.dispatch('createPost',newPost).then(()=>{
          createMessage('发表成功，2s后跳转到文章','success',2000)
          setTimeout(()=>{
            router.push({name:'column',params:{id:column}})
          },2000)
         })
         
         
         }
       
        }
      }
  
      // const beforeUnload =(file:File) =>{
      //   const isJPG = file.type === 'image/jpeg'
      //   if(!isJPG){
      //     createMessage('上传图片只能是JPG格式','error')

      //   }
      //   return isJPG
      // }
     
      const onFileUploaded = (rawData:ResponseType<ImageProps>)=>{
        createMessage(`上传图片ID ${rawData.data._id}` ,'success')

      }
      const onFileUploadedError = (error:string)=>{
        createMessage('上传图片失败','error')

      }
      const uploadCheck = (file:File) =>{
        const result = beforeUploadCheck(file,{format:['image/jpeg','image/png']})
        const { passed , error} =result
        if(error==='format'){
          createMessage('请上传JPJ或者PNG格式的图片','error')
        }
        if(error==='size'){
          createMessage('上传图片大小不能超过1Mb','error')
        }
        return passed

      }
      return {
        titleRules,
        titleVal,
        contentVal,
        contentRules,
        onFormSubmit,
        uploadCheck,
        onFileUploaded,
        onFileUploadedError,
        handleFileUploaded,
        uploadedData,
        isEditMode
        
      }
    }
  })
  </script>
  <style>
  .create-post-page .file-upload-container {
    height: 200px;
    cursor: pointer;
  }
  .create-post-page .file-upload-container img {
    width: 100%;
    height: 100%;
    object-fit: cover;
  }
  .wrapper{
    width:200px;
    height:60px;
    position: absolute;
    left:50%;
    top:50%;
    transform: translate(-50%, -50%);
}
.circle{
    
    width:20px;
    height:20px;
    position: absolute;
    border-radius: 50%;
    background-color: aqua;
    left:15%;
    transform-origin: 50%;
    animation: circle .5s alternate infinite ease;
}

@keyframes circle{
    0%{
        top:60px;
        height:5px;
        border-radius: 50px 50px 25px 25px;
        transform: scaleX(1.7);
    }
    40%{
        height:20px;
        border-radius: 50%;
        transform: scaleX(1);
    }
    100%{
        top:0%;
    }
}
.circle:nth-child(2){
    left:45%;
    animation-delay: .2s;
}
.circle:nth-child(3){
    left:auto;
    right:15%;
    animation-delay: .3s;
}
.shadow{
    width:20px;
    height:4px;
    border-radius: 50%;
    background-color: rgba(0,0,0,.5);
    position: absolute;
    top:62px;
    transform-origin: 50%;
    z-index: -1;
    left:15%;
    filter: blur(1px);
    animation: shadow .5s alternate infinite ease;
}

@keyframes shadow{
    0%{
        transform: scaleX(1.5);
    }
    40%{
        transform: scaleX(1);
        opacity: .7;
    }
    100%{
        transform: scaleX(.2);
        opacity: .4;
    }
}
.shadow:nth-child(4){
    left: 45%;
    animation-delay: .2s
}
.shadow:nth-child(5){
    left:auto;
    right:15%;
    animation-delay: .3s;
}
.wrapper span{
    position: absolute;
    top:75px;
    font-family: 'Lato';
    font-size: 20px;
    letter-spacing: 12px;
    color: #fff;
    left:15%;
}
  </style>
  